import axios from 'axios';
import { refreshToken } from './user';

const http = axios.create({
    baseURL: "http://localhost:8080/api",
    timeout: 10000
});

const whiteList = [
    '/user/login',
    '/user/register'
];

http.interceptors.request.use(
    config => {
        const isWhitelisted = whiteList.some(path => config.url.includes(path));
        const token = localStorage.getItem('token');

        if (!isWhitelisted && token) {
            config.headers['token'] = token;
        }

        return config;
    },
    error => {
        return Promise.reject(error);
    }
);

// 添加响应拦截器
http.interceptors.response.use(
    response => {
        return response;
    },
    async error => {
        const originalRequest = error.config;
        
        // 如果是token过期错误 且 未曾尝试过刷新
        if (error.response?.status === 401 && !originalRequest._retry) {
            originalRequest._retry = true;
            
            try {
                // 尝试刷新token
                const response = await refreshToken();
                const newToken = response.data.token;
                
                // 更新localStorage中的token
                localStorage.setItem('token', newToken);
                
                // 更新原始请求的token
                originalRequest.headers['token'] = newToken;
                
                // 重试原始请求
                return http(originalRequest);
            } catch (refreshError) {
                // 刷新token失败，清除用户信息并跳转到登录页
                localStorage.removeItem('token');
                localStorage.removeItem('userInfo');
                // 不再强制跳转到登录页，而是让组件自行处理未登录状态
                return Promise.reject(refreshError);
            }
        }
        return Promise.reject(error);
    }
);

export default http;